/*
 * @Description: ------------ fileDescription -----------
 * @Author: snows_l snows_l@163.com
 * @Date: 2024-11-07 14:33:20
 * @LastEditors: snows_l snows_l@163.com
 * @LastEditTime: 2024-12-23 17:25:21
 * @FilePath: \Backstage\Server\src\utils\middleware.js
 */
const dotenv = require('dotenv').config({ path: './.env' });
const { generateSecretKey, verifyToken } = require('./handleToken');
const { handleError } = require('../utils/common.js');

// 预防xss攻击
function preventionXSSMW(req, res, next) {
  // 清理GET参数
  if (req.query) {
    for (let key in req.query) {
      req.query[key] = String(req.query[key]).trim().replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
    }
  }
  // 清理POST参数
  if (!req.url.includes('/article/add') && !req.url.includes('/article/edit') && !req.url.includes('/config/blog/update') && !req.url.includes('/config/bs/update')) {
    if (req.body) {
      for (let key in req.body) {
        req.body[key] = String(req.body[key]).trim().replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
      }
    }
  }

  // 无需登录验证的 api
  const noAuthUrl = ['/sys/login', '/sys/register', '/sys/captchaImage', '/sys/resetpwd', '/sys/logout', '/dict/detail?dictType=music_type', '/musics/list?isUnPage=false'];

  // 静态资源请求不需要登录验证 静态资源后缀
  const staticUrl = [
    'js',
    'css',
    'png',
    'jpg',
    'jpeg',
    'gif',
    'svg',
    'apk',
    'exe',
    'ico',
    'eot',
    'ttf',
    'woff',
    'woff2',
    'html',
    'mp3',
    'mp4',
    'avi',
    'flv',
    'wmv',
    'mov',
    'mkv',
    'rmvb',
    'm4v',
    'swf',
    'zip',
    'rar',
    'tar',
    'gz',
    '7z',
    'pdf',
    'doc',
    'docx',
    'xls',
    'xlsx',
    'ppt',
    'pptx'
  ];

  // 博客访问接口   以及 登录、注册等接口  以及静态资源访问 不需要验证
  if ((!req.headers['blog-token-unauth'] || req.headers['blog-token-unauth'] !== 'true') && !noAuthUrl.includes(req.url) && !staticUrl.includes(req.url.split('.').pop())) {
    // 验证token
    let token = req.cookies['bs-cookie'];
    // let token = req.headers.authorization && req.headers.authorization.split(' ')[1];
    try {
      const user = verifyToken(token);
      if (!user) throw new Error('JsonWebTokenError:token验证失败');
    } catch (error) {
      return handleError(res, error);
    }
  }
  next();
}

module.exports = {
  preventionXSSMW
};
